import axios from 'axios'

export default {
    namespaced:true,
    state:()=>({
        cart:[]
    }),
    mutations:{
        updataCart(state,cart){
            state.cart=cart
        },
        // 改变单项选中状态
        updateCartState(state,payload){
            let index = state.cart.findIndex(item=>item.id == payload.id)
            state.cart[index].goods_state=payload.value
        },
        // 改变单项数量的值
        updateCartCount(state,payload){
            let index = state.cart.findIndex(item=>item.id == payload.id)
            state.cart[index].goods_count=payload.value
        },
        // 全选影响小选
        isAll(state,payload){
            if(payload){
                state.cart.forEach(item=>item.goods_state = true)
            }else{
                state.cart.forEach(item=>item.goods_state = false)
            }
        }
    },
    getters:{
        allPrice(state){
            return state.cart.filter(item=>item.goods_state)
            .reduce((sum,item)=>sum+=item.goods_count * item.goods_price,0)
        },
        allCount(state){
            return state.cart.filter(item=>item.goods_state).
            reduce((sum,item)=>sum+=item.goods_count,0)
        }
    },
    actions:{
        async getCartList(context){
            const res = await axios.get('https://www.escook.cn/api/cart')
            context.commit('updataCart',res.data.list)
        }
    }
}